package com.example.heathy_me;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.heathy_me.utils.FriendControlAlarmReceiver;
import com.example.heathy_me.utils.RequestHelper;
import com.example.heathy_me.utils.User;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class Login extends AppCompatActivity {
    private String Url = "http://122.152.221.118:5000/user";
    private EditText Username;
    private EditText Password;
    private EditText Repassword;
    private Button login;
    private TextView promptText;
    private boolean is_login = true;
//    UserSQLiteDB  dbHelper;

    MyApplication app;
    void changeMode()
    {
        if(is_login)
        {
            Repassword.setVisibility(View.VISIBLE);
            login.setText("注    册");
            promptText.setText("用户登录");
            is_login = false;
        }
        else {
            Repassword.setVisibility(View.GONE);
            login.setText("登    录");
            promptText.setText("用户注册");
            is_login = true;
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        app = (MyApplication) getApplication();
        setContentView(R.layout.activity_login);
        Username =(EditText)findViewById(R.id.username);
        Password =(EditText)findViewById(R.id.password);
        Repassword =(EditText)findViewById(R.id.re_password);
        login = (Button)findViewById(R.id.loginBtn);
        promptText = (TextView)findViewById(R.id.promptText);
        promptText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeMode();

            }

        });
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                String username="";
                String password="";
                String repassword="";

//                dbHelper=new UserSQLiteDB(Login.this,"User.db",null,2);
//                SQLiteDatabase db1=dbHelper.getReadableDatabase();
//                Cursor cursor=db1.query("user",null,null,null,null,null,null);
//                if(cursor.moveToLast()){
//                    username = cursor.getString(cursor.getColumnIndex("username"));
//                    password = cursor.getString(cursor.getColumnIndex("password"));
//                    Username.setText(username);
//                    Password.setText(password);
//                }
//                cursor.close();
                username=Username.getText().toString();
                password=Password.getText().toString();

                //Log.d("MainActivity", "username:" + username);
                //login
                RequestHelper r = new RequestHelper();
                String json = "";

                if(is_login){
                    if(username.isEmpty() || password.isEmpty())
                    {
                        Toast.makeText(Login.this, "帐号密码不能为空！", Toast.LENGTH_LONG).show();
                    }
                    else {
                        Url = app.getUrl()+"user?username=" + username + "&password=" + password;
                        try {
                            json = r.run(Url);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        JSONObject jsonObject;
                        int status = 0;
                        try {
                            jsonObject = new JSONObject(json);
                            status = jsonObject.getInt("status");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (json.isEmpty() || status ==0)
                        {

                            Toast.makeText(Login.this, "帐号密码错误！", Toast.LENGTH_LONG).show();
                        }
                        else
                        {
                            User user = r.JSONtoUser(json);
                            app.setUser(user);
//                            Log.d("MainActivity", "user:" + app.getUser().getId());
//                            dbHelper=new UserSQLiteDB(Login.this,"User.db",null,2);
//                            SQLiteDatabase db=dbHelper.getWritableDatabase();
//                            if (db.isOpen()) {
//                                ContentValues values = new ContentValues();
//                                values.put("username",username);
//                                values.put("password", password);
//                                db.insert("user",null,values);
//                            }
//                            db.close();

                            Toast.makeText(Login.this, "登录成功！", Toast.LENGTH_LONG).show();

                            if(app.isLogin())
                            {

                                RequestHelper req = new RequestHelper();
                                try {
                                    String jsons = req.friend_get(app.getUrl()+"friendnotice/"+app.getUser().getId());
                                    JSONObject Object = new JSONObject(jsons);
                                    status = Object.getInt("status");
                                    if(status == 1)
                                    {
                                        Log.d("MainActivity", "status:" + status);


                                        Calendar instance = Calendar.getInstance();
                                        instance.set(Calendar.HOUR_OF_DAY, 0);//小时
                                        instance.set(Calendar.MINUTE, 0);//分钟
                                        instance.set(Calendar.SECOND, 0);//秒
                                        AlarmManager alarmService = (AlarmManager) Login.this.getSystemService(ALARM_SERVICE);
                                        Intent alarmIntent = new Intent(Login.this, FriendControlAlarmReceiver.class).setAction("intent_alarm_log");
                                        PendingIntent broadcast = PendingIntent.getBroadcast(Login.this, 0, alarmIntent, 0);//通过广播接收
                                        alarmService.set(AlarmManager.RTC_WAKEUP, instance.getTimeInMillis() , broadcast);
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                                Intent intent=new Intent(Login.this,MainActivity.class);
                                startActivity(intent);


                            }
                        }

                    }

                }
                else {
                    password=Password.getText().toString();
                    repassword=Repassword.getText().toString();
                    Log.d("MainActivity", "repassword:" + password);
                    Log.d("MainActivity", "repassword:" + repassword);
                    if(username.isEmpty() || password.isEmpty() ||repassword.isEmpty())
                    {
                        Toast.makeText(Login.this, "帐号密码不能为空！", Toast.LENGTH_LONG).show();
                    }
                    else {
                        if(!password.equals(repassword))
                        {
                            Toast.makeText(Login.this, "两次输入的密码不一致！", Toast.LENGTH_LONG).show();
                        }
                        else {
                            Map map = new HashMap();
                            map.put("username", username);
                            map.put("password", password);
                            JSONObject obj = new JSONObject(map);
                            try {
                                r.register(app.getUrl()+"user/register",obj.toString());
                                Toast.makeText(Login.this, "注册成功！", Toast.LENGTH_LONG).show();
                                changeMode();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }
            }
        });

    }
}
